/**
 * 模拟锁的作用
 * @author: sundx
 * @date: 2020-05-27 16:59:38
 * @Last Modified by: sundx
 * @Last Modified time: 2020-05-27 17:24:33
 */
#include <iostream>
#include <pthread.h>
#include <string.h>
#include <unistd.h>

void *demo(void *argv);
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

int main() {
  pthread_t tid;
  int ret;
  ret = pthread_create(&tid, NULL, demo, nullptr);
  if (ret < 0) {
    std::cout << "pthread_create failed " << strerror(ret) << std::endl;
  }
  while (1) {
    ret = pthread_mutex_lock(&mutex); // 加锁
    if (ret < 0) {
      std::cout << "f lock failed" << strerror(ret) << std::endl;
    }
    std::cout << "HELLO";
    sleep(rand() % 2);
    std::cout << " WORLD" << std::endl;
    ret = pthread_mutex_unlock(&mutex); // 解锁
    if (ret < 0) {
      std::cout << "f unlock failed" << strerror(ret) << std::endl;
    }
    sleep(rand() % 2);
  }
  pthread_mutex_destroy(&mutex);

  pthread_exit(nullptr);
}
void *demo(void *argv) {
  int ret;
  while (1) {
    ret = pthread_mutex_lock(&mutex); // 加锁
    if (ret < 0) {
      std::cout << "son lock failed" << strerror(ret) << std::endl;
    }
    std::cout << "hello";
    sleep(rand() % 2);
    std::cout << " world" << std::endl;
    ret = pthread_mutex_unlock(&mutex); // 解锁
    if (ret < 0) {
      std::cout << "son unlock failed" << strerror(ret) << std::endl;
    }
    sleep(rand() % 2);
  }
  return nullptr;
}